package com.tungse;

import cn.hutool.core.collection.ListUtil;
import lombok.Data;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author : Tungse
 * @Date: 2025/7/9 11:08
 * @Description:
 */
public class TestAll {

    public static void main(String[] args) throws InterruptedException {
        new TestAll().test01();
    }

    public void test01 () throws InterruptedException {

        final Object lock = new Object();
        A a = new A();
        AtomicInteger cnt = new AtomicInteger(0);
        AtomicInteger cntCon = new AtomicInteger(0);
        Thread production = new Thread(() -> {
            while (true) {
                try {
                    synchronized (lock){
                        while(cnt.get() >= 10) {
                            System.out.println("消费不足， 生产慢一点;"+"未消费数量："+cnt.get() +"; 消费数量：" + cntCon.get());
                            lock.wait();
                        }
                    }
                    cnt.incrementAndGet();
                    a.getBq().put(UUID.randomUUID().toString());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }, "production");


        Thread consume = new Thread(() -> {
            while (true){
                try {
                    System.out.println(Thread.currentThread().getName() + "第"+cntCon.incrementAndGet()+"次消费"+a.getBq().take());
                    cnt.decrementAndGet();
                    Thread.sleep(1000);
                    synchronized (lock){
                        lock.notifyAll();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "consume0");
        Thread consume1 = new Thread(() -> {
            while (true){
                try {
                    System.out.println(Thread.currentThread().getName() +"第"+cntCon.incrementAndGet()+"次消费"+a.getBq().take());
                    cnt.decrementAndGet();
                    Thread.sleep(1000);
                    synchronized (lock){
                        lock.notifyAll();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "consume1");

        production.start();
        consume.start();
        consume1.start();
        production.join();
        consume.join();
        consume1.join();
    }


    @Data
    static class A {
        private BlockingQueue<String> bq = new ArrayBlockingQueue<>(10);
    }
}
